<?php

namespace controllers\admin;

use controllers\AdminApi;
use system\Route\Request;

/**
 * Class AuthGroup
 * @package controllers\admin
 * @auth    权限组
 */
class AuthGroup extends AdminApi {
    /**
     * 首页
     * @return array
     * @auth 权限组列表
     */
    public function index() {
        if ($this->isValid()) {
            $model = new \models\AuthGroup();
            list($page, $pageSize) = self::getPageInfo();
            $map = [];
            if (!$this->isSupper()) {
                $map['id notIn'] = [1];
            }
            $list = $model->where($map)->order('id asc')->field('id,name,create_time')->limit($page, $pageSize)->select();
            return self::returnJson($list, $model->count());
        }
    }

    /**
     * 保存
     *
     * @param Request $request
     *
     * @auth 保存/添加权限组
     *
     * @return string
     */
    public function edit(Request $request) {
        if ($this->isValid()) {
        	$id = $request->post('id' , 0);
        	$name = $request->post('name');
            $model = new \models\AuthGroup();
            if ($id > 0) {
                if (!$model->getFind($id, 'id')) {
                    return error('无效的信息');
                }
                $save = ['name' => $name];
                $model->where(['id' => $id])->update($save);
                $model->recordLog(2, $this->uid);
            } else {
                $model->create(['name' => $name]);
                $model->insert();
                $model->recordLog(1, $this->uid);
            }

            return success(($id ? '保存' : '添加') . '成功');
        }
    }

    /**
     * @param $id
     *
     * @auth 删除权限组
     *
     * @return string
     */
    public function delete($id) {
        if ($this->isValid()) {
            if ($id == 1) {
                return error('无法删除超级管理组');
            }
            $model = new \models\AuthGroup();
            $find  = $model->getFind($id);
            if (!$find) {
                return error('无效的信息');
            }
            $count = $model->getGroupCount($id);
            if ($count > 0) {
                return error('此权限组还有' . $count . '个用户');
            }
            $status = $model->delete($id);
            $model->recordLog(1, $this->uid, $find);

            return $status ? success('删除成功') : error('删除失败');
        }
    }

    /**
     * 分配权限
     *
     * @param int $id
     *
     * @auth 分配权限
     * @return string
     */
    public function rules($id = 0) {
        if ($this->isValid()) {
            $rules = self::getRules();
            // 读取本身的权限
            $model = new \models\AuthGroup();
            $find  = $model->getFind($id, 'id,rules');
            if (!$find) {
                return error('无效的管理组');
            }
            $auths = $find['rules'] ? json_decode($find['rules'], true) : [];
            foreach ($rules as $key => &$val) {
                $val['id'] = $key;
                $checked   = 0;
                if (count($val['children']) > 0) {
                    foreach ($val['children'] as $k => &$v) {
                        $v['checked'] = false;
                        if ($auths[ $val['name'] ] && array_key_exists($v['name'], $auths[ $val['name'] ]['children'])) {
                            $v['checked'] = true;
                            $checked++;
                        }
                        $v['id'] = $key . '-' . $k;
                    }
                }
                $val['checked'] = false;
                if ($auths[ $val['name'] ] && count($val['children']) == $checked) {
                    $val['checked'] = true;
                }
            }

            return success($rules);
        }

    }

    /**
     * 保存权限
     *
     * @param int $id
     *
     * @return string
     * @auth 保存分配权限
     */
    public function saveAuths($id = 0) {
        if ($this->isValid()) {
            $data = self::$post['data'];
            $data = json_decode($data, true);
            if (count($data) == 0) {
                return error('请选择一个权限吧');
            }
            $rules = [];
            foreach ($data as $key => $val) {
                $children = $val['children'];
                if (count($children) > 0) {
                    unset($val['children']);
                    $val['children'] = [];
                    foreach ($children as $k => $v) {
                        $val['children'][ $v['name'] ] = $v;
                    }
                }
                $rules[ $val['name'] ] = $val;
            }
            if (!$id) {
                return error('无效的授权分组');
            }
            $model = new \models\AuthGroup();
            if ($id == 1) {
                return error('无法调整超级管理员的权限');
            }
            $find = $model->getFind($id, 'id');
            if (!$find) {
                return error('管理组不存在');
            }
            $model->where(['id' => $id])->update(['rules' => json_encode($rules)]);
            $model->recordLog(2, $this->uid);

            return success('授权成功');
        }

    }

    /**
     * 获取分组
     * @return array
     * @white
     */
    public function groups() {
        if ($this->isValid()) {
            $group  = new \models\AuthGroup();
            $groups = $group->field('id,name')->select(true)->toArray('id', 'name');
            return self::returnJson($this->getSelectOptions($groups));
        }
    }
}